﻿using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Threading;
namespace SocketDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Loaded +=MainWindow_Load;
        }
        private void MainWindow_Load(object sender, EventArgs e)
        {
            //初始化控件
            txtSendMssg.Text = "测试数据";
            //打开Listener开始监听
            Thread thrListener = new Thread(new ThreadStart(Listen));
            thrListener.Start();
        }

       
        //监听数据
        private void Listen()
        {
            Socket listener = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);
            listener.Bind(new IPEndPoint(IPAddress.Any, 5658));
            Console.WriteLine("Listen starting ...");
            //不断监听端口
            while (true)
            {
                listener.Listen(0);
                Socket socket = listener.Accept();
                NetworkStream ntwStream = new NetworkStream(socket);
                StreamReader strmReader = new StreamReader(ntwStream);
                Dispatcher.Invoke(new PrintRecvMssgDelegate(PrintRecvMssg),
                    new object[] { strmReader.ReadToEnd() });
                socket.Close();
                
                
            }

            //程序的listener一直不关闭
            //listener.Close();
        }

        //线程内向文本框txtRecvMssg中添加字符串及委托
        private delegate void PrintRecvMssgDelegate(string s);
        private void PrintRecvMssg(string info)
        {
            textBox.Text += string.Format("[{0}]:{1}\r\n",
                DateTime.Now.ToLongTimeString(), info);
        }

        private void btnSend_Click_1(object sender, RoutedEventArgs e)
        {
            TcpClient tcpClient = new TcpClient();
            //tcpClient.Connect(IPAddress.Parse("170.0.0.78"), 2014);
            try {
                tcpClient.Connect(IPAddress.Parse("127.0.0.1"), 5658);
                Console.WriteLine("Socket Connected!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            NetworkStream ntwStream = tcpClient.GetStream();
            
            if (ntwStream.CanWrite)
            {
                Byte[] bytSend = Encoding.UTF8.GetBytes(txtSendMssg.Text);
                ntwStream.Write(bytSend, 0, bytSend.Length);
            }
            else
            {
                MessageBox.Show("无法写入数据流,估计是不能建立连接。");

                ntwStream.Close();
                tcpClient.Close();

                return;
            }

            ntwStream.Close();
            tcpClient.Close();
        }
    }
}
